<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h3> 求数组中两个最小的数</h3>

    <script>
        function find2smallest(arr)
    {
        let first =Number.MAX_VALUE;
        let second = Number.MAX_VALUE;
        let i;
        if(arr.length<2)
        {
            console.log("请确保数组中至少包括两个数值");
            return;
        }
        for(i=0;i<arr.length;i++)
        {
            //若arr[i]小于最小first，则first进行数据更新，同时原first值作为second的参考值
            if(arr[i]<first)
            {
                second = first;
                first = arr[i];
            }
            //arr[i]！=first,排除重复数值
            //上面的if循环保证first最小,必然满足arr[i]>=first,如此时arr[i]<second,则可能为第二小数
           else if(arr[i]<second && arr[i]!=first)
           {
               second =arr[i];
           }
        }
         if(second === Number.MAX_VALUE)
        {
               console.log("没有第二小的数值");
        } 
        else
        {
               console.log("first:"+first);
               console.log("second:"+second);
        }
    }
    //let arr = [ 2,3,12,9, 13, 1, 10, 34, 1 ]
    let arr =[-2,-1,5,2,10,8,4];
    find2smallest(arr);
    </script>

</body>
</html>